﻿using UnityEngine;
using UnityEditor;

namespace HKTools
{
    [InitializeOnLoad]
    public class HK_PrefabModificationDetector
    {
        static HK_PrefabModificationDetector()
        {
            EditorApplication.hierarchyWindowItemOnGUI += HierarchyItemCallback;
        }

        static void HierarchyItemCallback(int instanceID, Rect selectionRect)
        {
            GameObject obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;

            // 剔除最上面的scene物体，检查是否在ForDesign下面，不是则返回
            if (obj == null || !IsUnderParent(obj, "ForDesign"))
                return;

            // 判断当前obj是否为预设体的根节点，不是则返回
            if (obj != PrefabUtility.GetOutermostPrefabInstanceRoot(obj))
                return;

            // 检查是否是预制体实例，且未应用
            if (PrefabUtility.HasPrefabInstanceAnyOverrides(obj, false) && PrefabUtility.GetPrefabInstanceStatus(obj) == PrefabInstanceStatus.Connected)
            {
                Rect buttonRect = new Rect(selectionRect.xMax - 144, selectionRect.yMin + 2, 40, 16);

                if (GUI.Button(buttonRect, "更新"))
                {
                    // 应用预设体实例的更改
                    PrefabUtility.ApplyPrefabInstance(obj, InteractionMode.UserAction);
                }
            }
        }

        static bool IsUnderParent(GameObject obj, string parentName)
        {
            Transform current = obj.transform;

            // 确保当前对象本身不是ForDesign
            if (current.name == parentName)
                return false;

            // 遍历父级对象，检查是否在指定的父级对象下
            while (current != null)
            {
                if (current.name == parentName)
                {
                    return true;
                }
                current = current.parent;
            }
            return false;
        }
    }
}